<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <el-button
          style="float: right"
          class="changePostion"
          type="primary"
          @click="handleSearchList"
          size="s米糕"
        >
          查询搜索
        </el-button>
        <el-button
          style="float: right; margin-right: 15px"
          class="changePostion"
          @click="handleResetSearch"
          size="s米糕"
        >
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="s米糕">
          <el-form-item label="派单类型：">
            <el-select
              @change="changeAssignType"
              v-model="listQuery.assignTypeId"
              clearable
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in assignType"
                :key="item.id"
                :label="item.value"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="电邀姓名：">
            <el-select
              v-model="listQuery.invitationId"
              clearable
              filterable
              placeholder="请选择"
            >
              <el-option-group
                v-for="item in invitationDepartment"
                :key="item.id"
                :label="item.name"
              >
                <el-option
                  v-for="user in item.users"
                  :key="user.id"
                  :label="user.name"
                  :value="user.id"
                >
                </el-option>
              </el-option-group>
            </el-select>
          </el-form-item>
          <el-form-item label="城市：">
            <el-select
              v-model="listQuery.cityId"
              clearable
              filterable
              placeholder="请选择城市"
            >
              <el-option
                v-for="item in citys.options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="派单数量：">
            <el-input-number v-model="listQuery.assignCount" />
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表（{{ list.length }}）</span>
    </el-card>
    
    <component ref="table" name="table" 
      :listLoading="listLoading" 
      :list="list" 
      :is='assignOrderPage[listQuery.assignTypeId]'
    >
    </component>


    <div class="btn-container">
      <el-button type="primary" class="btn" @click="onPass">回传探马</el-button>
    </div>

    <!-- <div class="pagination-container" style="
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          padding-bottom: 20px;
        ">
        <el-pagination background @current-change="handleCurrentChange" layout="total, prev, pager, next,jumper"
          :page-size="pageSize" :total="allResult.length">
        </el-pagination>
      </div> -->
  </div>
</template>
  <script>
import { mapState } from "vuex";

import {
  getObtainOrganizationalStructure,
  returningToExploreHorses,
  getCitys,
  dispatchClient,
  getDispatchClient,
  getObtainOrganizationalStructureTotalNumber,
} from "../../api/assign";
import { DEPARTMENT_SEARCH, ASSIGN_ORDER_TYPE, ASSIGN_ORDER_PAGE } from "../../contanst/data";
import { sleep } from "../../utils/time";
import { fetchAllRoleList } from "@/api/role";
import { formatDate } from "@/utils/date";

export default {
  name: "eId",

  components: {
    sea: () => import("./component/sea.vue"),
    normal: () => import("./component/normal.vue")
  },

  data() {
    return {
      listQuery: Object.assign({}, DEPARTMENT_SEARCH),
      list: [],
      assignType: ASSIGN_ORDER_TYPE,
      assignOrderPage: ASSIGN_ORDER_PAGE,
      currentPage: 1,
      listLoading: false,
      dialogVisible: false,
      allocDialogVisible: false,
      allocRoleIds: [],
      allRoleList: [],
      citys: {},
      // 全部结果
      allResult: [],
      // 电邀部
      invitationDepartment: [],
      // 二道
      designatedNegotiator: {},
      allocAdminId: null,
      value: "",
      askForLeave: null,
      searchAskForLeave: null,
      status: "",
      urbanList1: [],
      urbanList2: [],
      allDagongren: [],
      pageSize: 50,
      total: 0,
    };
  },
  created() {
    getObtainOrganizationalStructure({}, this);

    getCitys(this);
  },

  methods: {
    formatDate,

    changeAssignType(value) {
      this.list = [];
    },

    onPass() {
      returningToExploreHorses(this.listQuery, this);
    },

    async searchAreaChange(val) {
      if (val) {
        const data = await this.getUrbans({ id: val });
        this.urbanList1 = data;
        this.listQuery.cityId = data[0].id;
      } else {
        this.urbanList1 = [];
        this.listQuery.cityId = null;
      }
    },

    async submitAreaChange(val) {
      if (val) {
        const data = await this.getUrbans({ id: val });
        this.urbanList2 = data;
        this.admin.cityId = data[0].id;
      } else {
        this.urbanList2 = [];
        this.admin.cityId = null;
      }
    },

    //排序 倒序
    sortList(a, b) {
      console.log(this.list);
      this.list.length &&
        this.list.sort((a, b) => {
          return b.id - a.id;
        });
    },

    // 弹窗关闭回调
    closed() {
      this.$refs.adminForm.clearValidate();
    },
    // 地区省份
    getAreas() {
      getArea({
        id: 0,
      }).then((response) => {
        if (response.data && response.data.length) {
          this.$store.commit("SET_AREAS", response.data);
        }
      });
    },
    // 获取市区
    async getUrbans(params) {
      const res = await getUrban(params);
      return res.data || [];
    },
    handleResetSearch() {
      this.status = "";
      this.cityValue = null;
      this.listQuery = Object.assign({}, defaultListQuery);
      this.searchAskForLeave = null;
      this.handleSearchList();
    },
    async handleSearchList() {
      this.listLoading = true;
      dispatchClient(this.listQuery, this).then(async () => {
        
        let time = 3000;
        if (this.listQuery.assignTypeId > 1) {
          time = 15000;
        }
        await sleep(time);

        getDispatchClient(this.listQuery, this);

        this.listLoading = false;
      }).catch(error => {
        console.log("error: ", error)
      });
    },

    async getTanmaData(param, index) {
      await getObtainOrganizationalStructureTotalNumber(param, this);
    },

    async handleUpdate(index, row) {
      this.dialogVisible = true;
      this.isEdit = true;
      this.admin = Object.assign({}, row);
      this.urbanList2 = await this.getUrbans({ id: this.admin.areaId });
      if (this.admin.cityId === 0) {
        this.admin.cityId = null;
      }
      if (row.leaveStart > 0 && row.leaveEnd > 0) {
        this.askForLeave = [row.leaveStart * 1000, row.leaveEnd * 1000];
      } else {
        this.askForLeave = null;
      }
    },
    handleDialogConfirm() {
      this.$confirm("是否要确认?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {});
    },
    handleAllocDialogConfirm() {
      this.$confirm("是否要确认?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {});
    },
    handleSelectRole(index, row) {
      this.allocAdminId = row.id;
      this.allocDialogVisible = true;
      this.getRoleListByAdmin(row.id);
    },

    // 更新地区搜索列表
    updateCityOptions() {
      this.allParams.pageNum = 1;
      this.allParams.lastId = 0;
      this.getAllDaGongren();
    },

    getList() {
      this.listLoading = true;
      staffListSearch(this.listQuery).then((response) => {
        this.listLoading = false;
        this.list = response.data.data;
        this.total = response.data.total;
        this.pageSize = response.data.pageSize;
        this.sortList();
        this.$forceUpdate();
      });
    },
    getAllRoleList() {
      fetchAllRoleList().then((response) => {
        this.allRoleList = response.data;
      });
    },
    getRoleListByAdmin(adminId) {
      getRoleByAdmin(adminId).then((response) => {
        let allocRoleList = response.data;
        this.allocRoleIds = [];
        if (allocRoleList != null && allocRoleList.length > 0) {
          for (let i = 0; i < allocRoleList.length; i++) {
            this.allocRoleIds.push(allocRoleList[i].id);
          }
        }
      });
    },

    handleSizeChange(val) {
      this.listQuery.pageNum = 1;
      this.listQuery.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      let start = (val - 1) * this.pageSize;

      let limit = start + this.pageSize;

      this.list = [];

      for (start; start < limit; start++) {
        if (!this.allResult[start]) {
          continue;
        }

        this.list.push(this.allResult[start]);
      }
    },
    handleAdd() {
      this.dialogVisible = true;
      this.isEdit = false;
      this.admin = Object.assign({}, defaultAdmin);
      this.askForLeave = null;
    },
    handleStatusChange(index, row) {
      this.$confirm("是否要修改该状态?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          updateStaff(row).then((response) => {
            this.$message({
              type: "success",
              message: "修改成功!",
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消修改",
          });
          this.getList();
        });
    },
    handleDelete(index, row) {
      this.$confirm("是否要删除该用户?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        deleteAdmin(row.id).then((response) => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getList();
        });
      });
    },
  },

  watch: {
    askForLeave(newVal) {
      if (newVal) {
        this.admin.leaveStart = newVal[0];
        this.admin.leaveEnd = newVal[1];
      }
    },
  },
  computed: {
    tooltipShow() {
      return (row) => {
        let start = new Date(row.leaveStart * 1000).getTime();
        let end = new Date(row.leaveEnd * 1000).getTime();
        let now = new Date().getTime();
        if (now < end) {
          return true;
        } else {
          return false;
        }
      };
    },
    formatDateTime() {
      return (time) => {
        if (time == null || time === "") {
          return "N/A";
        }
        let date = new Date(time);
        return formatDate(date, "yyyy/MM/dd hh:mm:ss");
      };
    },
    ...mapState(["areas"]),
    workStatuss() {
      return (s, e) => {
        const time = new Date().getTime() / 1000;
        if (s > 0 && e > 0) {
          if (time >= s && time <= e) {
            return "请假";
          } else {
            return "正常";
          }
        }
        return "正常";
      };
    },
  },
};
</script>
  <style scoped>
.my-dialog :deep(.el-dialog) {
  min-width: 700px;
  max-width: 100%;
}

.btn-container {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  margin-top: 25px;
  clear: both;
  position: relative;
  top: 9px;
  width: 100%;
}

.changePostion {
  margin-top: 1.1%;
}
</style>
    
    
    